export function adapterGoods(goods) {
  const { stocks = [], stock = {}, name, subtitle, image, id, album_pics, is_sku } = goods;
  const { price, market_price, qty, sold_qty } = stock;

  const skus = [];
  stocks.forEach((x) => {
    const rows = JSON.parse(x.json);
    rows.forEach((s) => {
      let sku = skus.find((t) => t.id == s.kid);
      if (!sku) {
        sku = { id: s.kid, name: s.k, parent_id: 0, children: [] };
        skus.push(sku);
      }
      if (!sku.children.find((x) => x.id === s.vid)) {
        sku.children.push({ id: s.vid, name: s.v, parent_id: s.kid });
      }
    });
  });

  const sku_prices = (is_sku ? stocks : [stock]).map((x) => {
    const { product_id, image, identify, price, market_price, qty, sold_qty, json, id } = x;
    return {
      goods_sku_price_id: id,
      goods_id: product_id,
      stock: qty,
      image,
      goods_sku_ids: identify,
      goods_sku_text: JSON.parse(json).map((x) => x.v),
      price,
      original_price: market_price,
      sales: sold_qty,
      disabled: false,
    };
  });
  // console.log(skus);
  return {
    id,
    image,
    is_sku,
    images: album_pics?.split(','),
    title: name,
    subtitle,
    stock: qty,
    sales: sold_qty,
    price: [price],
    original_price: market_price,
    service: [],
    params: [],
    skus,
    sku_prices,
    stock_show_type: 'exact',
  };
}
export function adapterCart(item) {
  // console.log(item);
  const { price, json, qty, image, product_id, id } = item.stock || {};
  const goods_sku_text = JSON.parse(json)
    .map((x) => x.v)
    .join(' ');
  return {
    ...item,
    goods_id: product_id,
    goods_sku_price_id: id,
    goods: { ...item.goods, title: item.goods?.name },
    sku_price: {
      price,
      image,
      goods_sku_text,
      stock: qty,
    },
  };
}

export default { adapterGoods, adapterCart };
